<template>
  <p-form-model
    ref="form"
    class="account-login"
    :model="form"
    :rules="rules"
    @keyup.enter.native="submit"
  >
    <p-form-model-item v-if="errMsg">
      <p-alert type="error" show-icon :message="errMsg" />
    </p-form-model-item>
    <p-form-model-item prop="username">
      <p-input
        v-model.trim="form.username"
        size="large"
        placeholder="请输入用户名"
      >
        <p-icon slot="prefix" type="user" />
      </p-input>
    </p-form-model-item>
    <p-form-model-item prop="password">
      <p-input
        v-model="form.password"
        :type="pwdInvisible ? 'password' : 'text'"
        size="large"
        placeholder="请输入密码"
      >
        <p-icon slot="prefix" type="lock" />
        <p-icon
          slot="suffix"
          :type="pwdInvisible ? 'eye-invisible' : 'eye'"
          @click="pwdInvisible = !pwdInvisible"
        />
      </p-input>
    </p-form-model-item>
    <p-form-model-item>
      <p-button
        type="primary"
        size="large"
        style="width: 100%"
        :loading="loading"
        @click="submit"
      >
        登录
      </p-button>
    </p-form-model-item>
  </p-form-model>
</template>

<script>
import { timeFix } from '@/utils';

export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      pwdInvisible: true,
      rules: {
        username: [
          { required: true, whitespace: true, message: '请输入用户名' },
        ],
        password: [{ required: true, whitespace: true, message: '请输入密码' }],
      },
      loading: false,
      errMsg: '',
    };
  },
  methods: {
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch('login', this.form)
            .then((res) => {
              if (res.code === 0) {
                this.loginSuccess();
              } else if (res.code === 406) {
                this.$emit('multiTenant', {
                  tenantList: res.data,
                  loginData: this.form,
                });
              } else {
                this.loginError(res.msg);
              }
            })
            .catch((err) => {
              console.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    loginError(errMsg) {
      this.errMsg = errMsg || this.errMsg;
    },
    loginSuccess() {
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`,
      });
      this.$router.push({
        path: 'work-bench',
      });
    },
  },
};
</script>
